package com.carson.undergo.ui.adapter.cart;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.carson.undergo.R;
import com.carson.undergo.ui.activity.home.CartDetailUI;
import com.carson.undergo.utils.bean.CartGoodsBean;
import com.model.common.utils.always.StringUtils;
import com.model.common.utils.always.ToastUtils;

import java.util.List;

/**
 * Create by Carson on 2021/12/24.
 * Android仿饿了么购物车功能适配器
 */
public class CartGoodsAdapter extends RecyclerView.Adapter {

    private final List<CartGoodsBean> mData;
    private int mAmountLeft;
    private int mReduceLeft;
    private int mAddLeft;
    private final CartDetailUI cartActivity;
    private final Context mContext;

    public CartGoodsAdapter(Activity activity, Context mContext, List<CartGoodsBean> list) {
        mData = list;
        this.cartActivity = (CartDetailUI) activity;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart_goods,
                parent, false);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        final MyHolder myHolder = (MyHolder) holder;
        myHolder.setItem(position);
        final CartGoodsBean goodsBean = mData.get(position);
        myHolder.itemName.setText(goodsBean.getGoodsName());
        myHolder.itemSku.setText(goodsBean.getSku());
        myHolder.itemPrice.setText(StringUtils.formatDouble(goodsBean.getSellPrice(), true));

        final long[] clickTime = {0};
        //点击加号
        myHolder.itemPlus.setOnClickListener(view -> {
            //屏蔽快速点击加入购物车问题
            if (System.currentTimeMillis() - clickTime[0] <= 1000) {
                return;
            }
            clickTime[0] = System.currentTimeMillis();

            if (goodsBean.getCount() >= goodsBean.getStoreNumber()) {
                ToastUtils.showMessage(mContext, "商品库存不足");
                return;
            }
            //如果该商品数量为0就进行 该动画
            if (goodsBean.getCount() == 0) {
                myHolder.itemMinus.setVisibility(View.VISIBLE);
                myHolder.itemCartNumber.setVisibility(View.VISIBLE);
                AnimatorSet set = new AnimatorSet();
                //减号
                ObjectAnimator ta1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "translationX", mAddLeft - mReduceLeft, 0);
                ObjectAnimator ra1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "rotation", 0, 360);
                ObjectAnimator aa1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "alpha", 0, 1);

                //数字
                ObjectAnimator ta2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "translationX", mAddLeft - mAmountLeft, 0);
                ObjectAnimator ra2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "rotation", 0, 360);
                ObjectAnimator aa2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "alpha", 0, 1);
                set.play(ta1).with(ra1).with(ta2).with(ra2).with(aa1).with(aa2);
                set.setDuration(500).start();
            }

            //得到加号在屏幕的坐标
            int[] addLocation = new int[2];
            view.getLocationInWindow(addLocation);
            //得到购物车图标的坐标
            int[] cartLocation = cartActivity.getCartLocation();
            //添加一个imageview
            final ImageView iv = new ImageView(view.getContext());
            iv.setBackgroundResource(R.drawable.icon_plus);
            RelativeLayout.LayoutParams lp =
                    new RelativeLayout.LayoutParams(view.getWidth(), view.getHeight());
            lp.leftMargin = addLocation[0];
            lp.topMargin = addLocation[1] - view.getHeight();

            cartActivity.getContainer().addView(iv, lp);
            //横向移动
            ObjectAnimator oaX = ObjectAnimator.ofFloat(iv, "translationX",
                    cartLocation[0] - addLocation[0] + view.getWidth() / 2);
            //纵向
            ObjectAnimator oaY = ObjectAnimator.ofFloat(iv,
                    "translationY", cartLocation[1] - addLocation[1]);
            oaX.setInterpolator(new LinearInterpolator());
            oaY.setInterpolator(new AccelerateInterpolator());
            AnimatorSet set = new AnimatorSet();
            set.play(oaX).with(oaY);
            set.setDuration(500).start();
            set.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onAnimationEnd(Animator animation) {
                    //移除这个view
                    cartActivity.getContainer().removeView(iv);
                    //更新购物车
                    goodsBean.setCount(goodsBean.getCount() + 1);
                    if (cartActivity.cartList.size() > 0) {
                        for (int i = 0; i < cartActivity.cartList.size(); i++) {
                            if (cartActivity.cartList.get(i).getSkuId() == goodsBean.getSkuId()) {
                                cartActivity.cartList.get(i).setCount(goodsBean.getCount());
                                break;
                            } else if (i == cartActivity.cartList.size() - 1) {
                                cartActivity.cartList.add(goodsBean);
                                break;
                            }
                        }
                    } else {
                        cartActivity.cartList.add(goodsBean);
                    }
                    ((MyHolder) holder).itemCartNumber.setText(String.valueOf(goodsBean.getCount()));
                    cartActivity.mCount++;
                    cartActivity.setCartNumber();
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        });

        //点击减号
        myHolder.itemMinus.setOnClickListener(view -> {
            final CartGoodsBean cartModel = mData.get(position);
            //如果该商品数量为1就进行这个动画
            if (cartModel.getCount() == 1) {
                AnimatorSet set = new AnimatorSet();
                //减号
                ObjectAnimator ta1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "translationX", 0, mAddLeft - mReduceLeft);
                ObjectAnimator ra1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "rotation", 0, 360);
                ObjectAnimator aa1 = ObjectAnimator.ofFloat(myHolder.itemMinus,
                        "alpha", 1, 0);

                //数字
                ObjectAnimator ta2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "translationX", 0, mAddLeft - mAmountLeft);
                ObjectAnimator ra2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "rotation", 0, 360);
                ObjectAnimator aa2 = ObjectAnimator.ofFloat(myHolder.itemCartNumber,
                        "alpha", 1, 0);
                set.play(ta1).with(ra1).with(ta2).with(ra2).with(aa1).with(aa2);
                set.setDuration(500).start();
                set.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                    }

                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        cartModel.setCount(cartModel.getCount() - 1);
                        myHolder.itemCartNumber.setText(String.valueOf(cartModel.getCount()));
                        if (cartModel.getCount() == 0) {
                            myHolder.itemCartNumber.setVisibility(View.INVISIBLE);
                            myHolder.itemMinus.setVisibility(View.INVISIBLE);
                        }
                        if (cartActivity.cartList.size() > 0) {
                            for (int i = 0; i < cartActivity.cartList.size(); i++) {
                                if (cartActivity.cartList.get(i).getSkuId() == goodsBean.getSkuId()) {
                                    if (cartActivity.cartList.get(i).getCount() == 0) {
                                        cartActivity.cartList.remove(cartModel);
                                    }
                                }
                            }
                        }
                        cartActivity.mCount--;
                        cartActivity.setCartNumber();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {
                    }
                });

            } else {
                cartModel.setCount(cartModel.getCount() - 1);
                if (cartActivity.cartList.size() > 0) {
                    for (int i = 0; i < cartActivity.cartList.size(); i++) {
                        if (cartActivity.cartList.get(i).getSkuId() == goodsBean.getSkuId()) {
                            cartActivity.cartList.get(i).setCount(cartModel.getCount());
                        }
                    }
                }
                myHolder.itemCartNumber.setText(String.valueOf(cartModel.getCount()));
                cartActivity.mCount--;
                cartActivity.setCartNumber();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        ImageView itemImage;
        TextView itemName, itemSku, itemPrice, itemCartNumber;
        ImageButton itemMinus, itemPlus;
        LinearLayout layoutAdd;

        public MyHolder(View itemView) {
            super(itemView);
            itemImage = itemView.findViewById(R.id.item_image);
            itemName = itemView.findViewById(R.id.item_name);
            itemSku = itemView.findViewById(R.id.item_sku);
            itemCartNumber = itemView.findViewById(R.id.item_cart_number);
            layoutAdd = itemView.findViewById(R.id.layout_add);
            itemMinus = itemView.findViewById(R.id.item_minus);
            itemPrice = itemView.findViewById(R.id.item_price);
            itemPlus = itemView.findViewById(R.id.item_plus);

            itemPlus.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            //得到加号的左边位置
                            mAddLeft = itemPlus.getLeft();
                            itemPlus.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });

            itemMinus.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            //得到减号的左边位置
                            mReduceLeft = itemMinus.getLeft();
                            itemMinus.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });

            itemCartNumber.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            //得到价格的左边位置
                            mAmountLeft = itemCartNumber.getLeft();
                            itemCartNumber.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });
        }


        public void setItem(int position) {
            CartGoodsBean cartModel = mData.get(position);
            itemName.setText(cartModel.getGoodsName());
            itemCartNumber.setText(String.valueOf(cartModel.getCount()));

            if (cartModel.getCount() > 0) {//数目大于0就显示
                itemMinus.setVisibility(View.VISIBLE);
                itemCartNumber.setVisibility(View.VISIBLE);
            } else {//数目小于0就隐藏
                itemMinus.setVisibility(View.INVISIBLE);
                itemCartNumber.setVisibility(View.INVISIBLE);
            }
        }
    }
}
